package top.jnaw.jee.utils;

import com.jfinal.core.Controller;

/**
 * Created by neo on 17-6-1.
 */
public class UA {

  public static final String MOBILE_KEY = "mobile";

  private static final String REDIRECT_MIS_LIST_FORMATTER = "%s/list";
  private static final String REDIRECT_MAIN_FORMATTER = "%s/main?%s";
  private static final String[] MOBILE_UA_KEYS = {
      "Android", "BB10", "Phone", "PlayBook",
  };

  /**
   * 判断请求是否来自移动平台
   */
  public static boolean isMobileDevice(Controller controller) {
    boolean result = false;
    final String ua = controller.getHeader("user-agent");

    for (String key : MOBILE_UA_KEYS) {
      if (ua.contains(key)) {
        result = true;
        break;
      }
    }

    return result;
  }

  /**
   * 将 index 请求跳转至 main 请求
   *
   * @param view 视图路径
   * @param param 新增参数
   * @param withOldParam 是否携带旧参数
   */
  public static void redirectMain(Controller controller, String view,
      String param, boolean withOldParam) {
    controller.redirect(String.format(REDIRECT_MAIN_FORMATTER, view, param),
        withOldParam);
  }

  /**
   * 跳转至 list 请求
   */
  public static void redirectMISList(Controller controller, String view) {
    controller.redirect(String.format(REDIRECT_MIS_LIST_FORMATTER, view));
  }

}
